﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TreeRenderingWithVisitor
{
    class XmlRenderer : IRenderer
    {
        private StringBuilder _builder = new StringBuilder();

        public string Render(ITree tree)
        {
            InsideNode(() =>
            {
                _Render(tree);
            }, tree);

            return _builder.ToString();
        }

        private void _Render(ITree tree)
        {
            if (tree.Children.Count > 0)
            {
                foreach (var child in tree.Children)
                {
                    InsideNode(() =>
                    {
                        _Render(child);
                    }, child);
                }
            }
        }

        private void InsideNode(Action action, ITree node)
        {
            _builder.Append("<element id=\"").Append(node.Id).Append("\" name=\"");
            _builder.Append(node.Name).Append("\">");
            action();
            _builder.Append("</element>");
        }
    }
}
